package org.chen.wordwave.act;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.hjq.toast.Toaster;

import org.chen.wordwave.R;
import org.chen.wordwave.act.adapter.BookListAdapter;
import org.chen.wordwave.base.BaseActivity;
import org.chen.wordwave.bean.BookList;
import org.chen.wordwave.bean.BookListData;
import org.chen.wordwave.bean.BookListData_s;
import org.chen.wordwave.tools.db.DBHelper;
import org.chen.wordwave.tools.http.ApiAddress;
import org.chen.wordwave.tools.http.HttpUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class BookListAct extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "BookListActivity";
    private final List<BookListData_s> bookDataList = new ArrayList<>();
    private DBHelper dbHelper;
    private BookListAdapter adapter;
    private MyAsyncTask myAsyncTask;
    private boolean hasCathe = false;
    private Context context;
    private boolean netAvailable = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public Integer getLayoutResId() {
        return R.layout.booklist_fragment;
    }

    @Override
    public void init() {
        context = this;
        netAvailable = HttpUtil.networkAvailable(context);

        initBookList();
        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myAsyncTask != null) {
            myAsyncTask.cancel(true);
            dbHelper.close();
        }

        View bottomBar = findViewById(R.id.botton_bar);
        if (bottomBar != null) {
            bottomBar.setVisibility(View.VISIBLE);
        }
    }

    private void initView() {
        TextView bookTitle = findViewById(R.id.is_checked);
        TextView my_favorites = findViewById(R.id.my_favorites);
        TextView translator = findViewById(R.id.translator);
        my_favorites.setOnClickListener(this);
        translator.setOnClickListener(this);
        RecyclerView recycler_booklist = findViewById(R.id.recycler_booklist);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        recycler_booklist.setLayoutManager(layoutManager);
        adapter = new BookListAdapter(context, bookDataList, bookTitle);
        recycler_booklist.setAdapter(adapter);
        if (hasCathe)
            bookTitle.setText(DBHelper.getBookTitle(context, 1));
        else
            bookTitle.setText(R.string.non);
    }

    private void initBookList() {
        dbHelper = new DBHelper(context, "Users.db", null, 1);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String sql = "select * from booklist;";
        Cursor cursor = db.rawQuery(sql, null);
        hasCathe = cursor.moveToFirst() && cursor.getCount() != 0;
        if (hasCathe) {
            do {
                BookListData_s bookListDatas = new BookListData_s();
                bookListDatas.setClass_id(cursor.getString(cursor.getColumnIndexOrThrow("class_id")));
                bookListDatas.setCourse_num(cursor.getInt(cursor.getColumnIndexOrThrow("course_num")));
                bookListDatas.setTitle(cursor.getString(cursor.getColumnIndexOrThrow("title")));
                bookListDatas.setWord_num(cursor.getString(cursor.getColumnIndexOrThrow("word_num")));
                bookListDatas.setMsg(cursor.getString(cursor.getColumnIndexOrThrow("msg")));
                bookDataList.add(bookListDatas);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
    }

    private void initData() {
        DBHelper.setDateNum(context, 1);

        if (!hasCathe) {
            if (netAvailable) {
                myAsyncTask = new MyAsyncTask();
                myAsyncTask.execute(new ApiAddress(context).getBookListAddress());
            } else {
                BookListData_s bookListDatas = new BookListData_s();
                bookListDatas.setTitle(getString(R.string.no_cache_no_network));
                bookDataList.add(bookListDatas);
            }
        } else {
            hasCathe = false; // 缓存数据已经加载完，故设为false
        }
    }

    private class MyAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {}

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(params[0]).build();
            try {
                Response response = client.newCall(request).execute();
                return Objects.requireNonNull(response.body()).string();
            } catch (IOException e) {
                return e.getMessage();
            }
        }
        @Override
        protected void onProgressUpdate(Integer... values) {}

        @Override
        protected void onPostExecute(String params) {
            try {
                SQLiteDatabase db = dbHelper.getReadableDatabase();
                db.execSQL("delete from booklist;");
                Gson gson = new Gson();
                runOnUiThread(()-> {
                    Log.e("MyAsyncTask",params);
                });
                BookList bookList = gson.fromJson(params, BookList.class);
                ArrayList<BookListData> dataList = bookList.getData();
                StringBuilder sql = new StringBuilder(
                        "insert into booklist (msg,title,class_id,word_num,course_num,existence_item) values ");
                for (int i = 0; i < dataList.size(); i++) {
                    for (int j = 0; j < dataList.get(i).getChildList().size(); j++) {
                        sql.append("('").append(bookList.getMsg()).append("','")
                                .append(dataList.get(i).getChildList().get(j).getTitle()).append("','")
                                .append(dataList.get(i).getChildList().get(j).getClassId()).append("','")
                                .append(dataList.get(i).getChildList().get(j).getWordNum()).append("','")
                                .append(dataList.get(i).getChildList().get(j).getCourseNum()).append("','")
                                .append(0).append("'),");
                        BookListData_s bookListDatas = new BookListData_s();
                        bookListDatas.setClass_id(dataList.get(i).getChildList().get(j).getClassId());
                        bookListDatas.setCourse_num(dataList.get(i).getChildList().get(j).getCourseNum());
                        bookListDatas.setTitle(dataList.get(i).getChildList().get(j).getTitle());
                        bookListDatas.setWord_num(dataList.get(i).getChildList().get(j).getWordNum());
                        bookListDatas.setMsg(bookList.getMsg());
                        bookDataList.add(bookListDatas);
                    }
                }
                sql.deleteCharAt(sql.length() - 1).append(";");
                adapter.notifyDataSetChanged();
                db.execSQL(sql.toString());
                db.close();
            } catch (Exception e) {
                Toaster.show(R.string.no_cache_no_network);
            }
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.my_favorites) {
            context.startActivity(new Intent(context, Favorites.class));
        } else if (id == R.id.translator) {
            context.startActivity(new Intent(context, Translator.class));
        }
    }
}
